package fun.werfamily.wf.gateway.util;

import com.alibaba.fastjson.JSON;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.geo.Circle;
import org.springframework.data.geo.GeoResults;
import org.springframework.data.redis.connection.RedisGeoCommands;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * @Author: Mr.WenMing Zhang
 * @Date: 2021-12-30 11:35
 * @Description:
 **/
@Slf4j
@Component
public class RedisUtil<T> {
    @Resource
    private RedisTemplate redisTemplate;
    private final TimeUnit TIME_UNIT = TimeUnit.SECONDS;

    /**
     * increment by bigDecimal
     *
     * @param key
     * @param value
     * @return
     */
    public BigDecimal increment(String key, BigDecimal value) {
        if (value == null) {
            return null;
        }
        double floatValue = value.doubleValue();
        try {
            double incrResult = redisTemplate.opsForValue().increment(key, floatValue);
            return BigDecimal.valueOf(incrResult);
        } catch (Exception ex) {
            log.error("redis执行increment发生异常：", ex.getMessage());
            return null;
        }
    }

    /**
     * increment by bigDecimal
     *
     * @param key
     * @param value
     * @return
     */
    public Long increment(String key, Long value) {
        if (value == null) {
            return null;
        }
        try {
            Long incrResult = redisTemplate.opsForValue().increment(key, value);
            return incrResult;
        } catch (Exception ex) {
            log.error("redis执行increment发生异常：", ex.getMessage());
            return null;
        }
    }

    /**
     * 保存String
     *
     * @param key
     * @param value
     * @param expire
     */
    public void saveString(String key, String value, long expire) {
        try {
            redisTemplate.opsForValue().set(key, value, expire, TIME_UNIT);
        } catch (Exception ex) {
            log.error("redis执行set发生异常：", ex.getMessage());
        }
    }

    /**
     * 获取String
     *
     * @param key
     * @return
     */
    public String getString(String key) {
        try {
            Object value = redisTemplate.opsForValue().get(key);
            if (Objects.nonNull(value)) {
                return value.toString();
            }
            return null;
        } catch (Exception ex) {
            log.error("redis执行get发生异常：", ex.getMessage());
            return null;
        }
    }


    /**
     * 保存单个对象
     *
     * @param key
     * @param value
     * @param expire
     */
    public void saveObject(String key, T value, long expire) {
        if (Objects.isNull(value)) {
            return;
        }

        try {
            String stringValue = JSON.toJSONString(value);
            redisTemplate.opsForValue().set(key, stringValue, expire, TIME_UNIT);
        } catch (Exception ex) {
            log.error("redis执行set发生异常：", ex.getMessage());
        }
    }

    /**
     * 设置过期时间
     *
     * @param key
     * @param expire
     */
    public void setExpire(String key, long expire) {
        try {
            redisTemplate.expire(key, expire, TIME_UNIT);
        } catch (Exception ex) {
            log.error("redis执行expire发生异常：", ex);
        }
    }

    /**
     * 单个对象setIfAbsent
     *
     * @param key
     * @param value
     * @param expire
     * @return
     */
    public boolean setIfAbsent(String key, T value, long expire) {
        try {
            if (Objects.isNull(value)) {
                return false;
            }
            String stringValue = JSON.toJSONString(value);
            return redisTemplate.opsForValue().setIfAbsent(key, stringValue, expire, TIME_UNIT);
        } catch (Exception ex) {
            log.error("redis执行setIfAbsent发生异常：", ex.getMessage());
            return false;
        }
    }

    /**
     * 获取对象
     *
     * @param key
     * @param tClass
     * @return
     */
    public T getObject(String key, Class<T> tClass) {
        if (StringUtils.isEmpty(key)) {
            return null;
        }
        String str = (String) redisTemplate.opsForValue().get(key);
        if (StringUtils.isEmpty(str)) {
            return null;
        }
        return JSON.parseObject(str, tClass);
    }

    /**
     * 列表头部批量添加元素
     *
     * @param key
     * @param objects
     */
    public void listLeftPushAll(String key, List<Object> objects) {
        if (StringUtils.isEmpty(key)) {
            return;
        }
        try {
            redisTemplate.opsForList().leftPushAll(key, objects);
        } catch (Exception e) {
            log.warn("Redis 执行出错message:{}", e.getMessage());
            e.printStackTrace();
        }
    }

    /**
     * @param key
     * @param objects
     */
    public void listRightPushAll(String key, List<Object> objects) {
        if (StringUtils.isEmpty(key)) {
            return;
        }
        try {
            redisTemplate.opsForList().rightPushAll(key, objects);
        } catch (Exception e) {
            log.warn("Redis 执行出错message:{}", e.getMessage());
            e.printStackTrace();
        }
    }

    /**
     * 获取列表置顶区间元素
     *
     * @param key
     * @param start
     * @param end
     * @param tClass
     * @return
     */
    public List<T> getListByRange(String key, Long start, Long end, Class<T> tClass) {
        if (StringUtils.isEmpty(key)) {
            return null;
        }
        List<T> list = new ArrayList<>();
        List<Object> range = redisTemplate.opsForList().range(key, start, end);
        for (Object o : range) {
            try {
                T t = (T) o;
                list.add(t);
            } catch (Exception e) {
                log.warn("Redis 执行出错message:{}", e.getMessage());
                e.printStackTrace();
                return list;
            }
        }
        return list;
    }

    /**
     * 列表头弹出一个元素
     *
     * @param key
     * @param tClass
     * @return
     */
    public T listLeftPop(String key, Class<T> tClass) {
        if (StringUtils.isEmpty(key)) {
            return null;
        }
        return (T) redisTemplate.opsForList().leftPop(key);
    }

    /**
     * 列表裁剪
     *
     * @param key
     * @param start
     * @param end
     */
    public void listLeftTrim(String key, Long start, Long end) {
        if (StringUtils.isEmpty(key)) {
            return;
        }
        redisTemplate.opsForList().trim(key, start, end);
    }

    /**
     * 判断key是否存在
     *
     * @param key
     * @return
     */
    public Boolean keyExists(String key) {
        if (StringUtils.isEmpty(key)) {
            return false;
        }
        return redisTemplate.hasKey(key);
    }

    /**
     * 获取列表size
     *
     * @param key
     * @return
     */
    public Long getListSize(String key) {
        if (StringUtils.isEmpty(key)) {
            return null;
        }
        return redisTemplate.opsForList().size(key);
    }

    /**
     * 添加经纬度
     *
     * @param key
     * @param iterable
     */
    public void geoBatchAdd(String key, Iterable iterable) {
        if (StringUtils.isEmpty(key)) {
            return;
        }
        redisTemplate.opsForGeo().add(key, iterable);
    }

    /**
     * 获取半径范围内的经纬度，降序排列并返回距离
     *
     * @param key
     * @param circle
     */
    public GeoResults<RedisGeoCommands.GeoLocation<T>> geoRadius(String key, Circle circle) {
        RedisGeoCommands.GeoRadiusCommandArgs geoRadiusCommandArgs = RedisGeoCommands.GeoRadiusCommandArgs.newGeoRadiusArgs();
        geoRadiusCommandArgs.sortAscending().includeDistance().hasLimit();
        GeoResults radius = redisTemplate.opsForGeo().radius(key, circle, geoRadiusCommandArgs);
        return radius;
    }

    /**
     * 删除key
     *
     * @param key
     */
    public void deleteKey(String key) {
        try {
            redisTemplate.delete(key);
        } catch (Exception ex) {
            log.error("redis执行delete发生异常：", ex.getMessage());
        }
    }

    /**
     * 保存BitMap
     *
     * @param key
     * @param offset
     */
    public void setBit(String key, long offset, boolean flag) {
        try {
            redisTemplate.opsForValue().setBit(key, offset, flag);
        } catch (Exception ex) {
            log.error("redis执行setBit发生异常：", ex.getMessage());
        }
    }

    /**
     * 获取BitMap
     *
     * @param key
     * @param userId
     */
    public Boolean getBit(String key, long userId) {
        try {
            return redisTemplate.opsForValue().getBit(key, userId);
        } catch (Exception ex) {
            log.error("redis执行getBit发生异常：", ex.getMessage());
        }
        return Boolean.FALSE;
    }

    /**
     * 保存set集合
     *
     * @param key
     * @param list
     */
    public void saveSet(String key, List<T> list, long expire) {
        if (CollectionUtils.isEmpty(list)) {
            return;
        }
        try {
            redisTemplate.opsForSet().add(key, list.toArray());
            redisTemplate.expire(key, expire, TimeUnit.SECONDS);
        } catch (Exception ex) {
            log.error("redis执行保存set集合发生异常：", ex.getMessage());
        }
    }

    /**
     * 获取set
     *
     * @param key
     * @return
     */
    public Set<T> setMembers(String key) {
        try {
            return redisTemplate.opsForSet().members(key);
        } catch (Exception ex) {
            log.error("redis获取set发生异常：", ex.getMessage());
        }
        return null;
    }

    /**
     * 判断是否包含
     *
     * @param key
     * @param target
     * @return
     */
    public Boolean isMember(String key, Object target) {
        try {
            return redisTemplate.opsForSet().isMember(key, target);
        } catch (Exception ex) {
            log.error("redis执行setBit发生异常：", ex.getMessage());
        }
        return Boolean.FALSE;
    }
}
